// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV,
  throwOnNotFound: false
})
const db = cloud.database();
const _ = db.command;
const $ = _.aggregate;

calcService = studioid => {
  return db.collection('service')
    .aggregate()
    .match({
      studioid: studioid
    })
    .project({
      isize: $.filter({
        input: '$nodes',
        as: 'item',
        cond: $.eq(['$$item.type', 'img'])
      }),
      size1: '$cover.size'
    }).project({
      size2: $.reduce({
        input: '$isize',
        initialValue: 0,
        in: $.sum(['$$value', '$$this.size']),
      }),
      size1: '$size1'
    })
    .group({
      _id: null,
      coversize: $.sum('$size1'),
      nodesize: $.sum("$size2")
    }).project({
      _id: '套系',
      size: $.add(['$coversize', '$nodesize'])
    })
    .end()
}

calcPortfolio = studioid => {
  return db.collection('portfolio')
    .aggregate()
    .match({
      studioid: studioid
    })
    .project({
      isize: $.filter({
        input: '$nodes',
        as: 'item',
        cond: $.eq(['$$item.type', 'img'])
      }),
      size1: '$cover.size'
    }).project({
      size2: $.reduce({
        input: '$isize',
        initialValue: 0,
        in: $.sum(['$$value', '$$this.size']),
      }),
      size1: '$size1'
    })
    .group({
      _id: null,
      coversize: $.sum('$size1'),
      nodesize: $.sum("$size2")
    }).project({
      _id: '作品',
      size: $.add(['$coversize', '$nodesize'])
    })
    .end()
}

calcOrder = studioid =>{
  return db.collection('picture')
  .aggregate()
  .match({
    studioid: studioid
  }).group({
    _id: '客户选片',
    size: $.sum(
      $.sum('$files.size')
    )
  }).end();
}

calcStudio = studioid => {
  return db.collection('gallary')
    .aggregate()
    .match({
      studioid: studioid
    }).group({
      _id: '素材库',
      size: $.sum(
        $.sum('$size')
      )
    })
    .end()
}

// 云函数入口函数
exports.main = async (event, context) => {
  const studioid = event.studioid;
  if (!studioid) {
    throw new Error('参数studioid为空');
  }
  return new Promise((resolve, reject)=>{
    let studioinfo = calcStudio(studioid);
    // let serviceinfo = calcService(studioid);
    // let portfolioinfo = calcPortfolio(studioid);
    let orderinfo = calcOrder(studioid);
    Promise.all([studioinfo, orderinfo]).then(res => {
      // console.log(res);
      let result = [];
      res.map((v,i)=>{
        if (v.list.length > 0){
          result.push({title: v.list[0]._id, size: v.list[0].size});
        }
      })
      resolve(result);
    }).catch(e=>{
      console.error(e);
      reject(e);
    })
  })
  
}